﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.ObjectModel;
using Microsoft.Office.Interop.Excel;
using MVVM.Core;

namespace ObjectModel.Excel
{
    public class LinkedRangesViewModel : ViewModelBase
    {
        private Application mApp;

    	public ObservableCollection<LinkedRange> LinkedRanges {
    		get { return _linkedRanges; }
    		set { _linkedRanges = value; }
    	}

		private ObservableCollection<LinkedRange> _linkedRanges = new ObservableCollection<LinkedRange>();

    	public List<TestBind> TestBinds { get; set; } 

        public LinkedRangesViewModel(Application app)
        {
            mApp = app;
        }

		public bool Checked { get { return true; }
    		set {}
    	}

		public LinkedRangesViewModel() { mApp = Globals.Application; }

        // TODO: rewrite more efficiently using LINQ
        public void CloseSourceWorkbooks()
        {
            List<Workbook> workbooks = new List<Workbook>();

            // Get a list of all unique workbooks opened programmatically.
            foreach (LinkedRange range in LinkedRanges)
            {
                if (range.SourceRange.CloseWorkbook)
                {
                    Workbook wb = range.SourceRange.Workbook;
                    if (!workbooks.Contains(wb))
                        workbooks.Add(wb);
                }
            }

            // Close the workbooks.
            foreach (Workbook wb in workbooks)
                wb.Close(false);
        }

        public void CreateLinkedRange()
        {
            Range range = mApp.Selection as Range;
            if (range != null)
            {
                CreateLinkedRange(range);
            }
        }
        
        public void CreateLinkedRange(Range range)
        {
            LinkedRanges.Add(new LinkedRange(range));
        }

        public void Restore()
        {
            // Deserialize linked ranges.
        }

        public void UpdateAll()
        {
            foreach (LinkedRange range in LinkedRanges)
                range.UpdateValues();

            CloseSourceWorkbooks();
        }

        public void Save()
        {
            // Serialize linked ranges.
        }
    }
}
